using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using System.Xml.Linq;
using Microsoft.Xna.Framework;

namespace WPCoco.Tilesets.Codecs
{
    class SimpleFormatReader : ITilesetReader
    {
        #region ITilesetReader Members

        public bool CanRead(XDocument document)
        {
            XElement tiles = document.Root as XElement;
            if (tiles == null) return false;
            if (tiles.Name != "Tiles") return false;
            XAttribute attr = tiles.Attribute(XName.Get("version"));
            if (attr == null) return false;
            if (attr.Value != "1.0") return false;
            return true;
        }

        public Tileset Read(XDocument document, Texture2D texture)
        {
            Tileset tileset = new Tileset();

            XName name = XName.Get("Definition");
            var defs = document.Document.Descendants(name);
            TextureFrame frame;
            float[] v;
            XAttribute attr; Vector2 p, s; Trim t;
            foreach (var item in defs)
            {
                attr = item.Attribute(XName.Get("Position"));
                v = ParserHelper.GetValues(attr.Value); p = new Vector2(v[0], v[1]);
                attr = item.Attribute(XName.Get("Size"));
                v = ParserHelper.GetValues(attr.Value); s = new Vector2(v[0], v[1]);
                attr = item.Attribute(XName.Get("Trim"));
                v = ParserHelper.GetValues(attr.Value); t = new Trim((int)v[0], (int)v[1], (int)v[2], (int)v[3]);

                frame = new TextureFrame()
                {
                    Texture = texture,
                    TextureRegion = new Rectangle((int)p.X, (int)p.Y, (int)s.X, (int)s.Y),
                    TextureTrim = t
                };

                attr = item.Attribute(XName.Get("Alias"));
                tileset.Add(frame);
                tileset.AddAlias(attr.Value, tileset.Count - 1);
            }

            return tileset;
        }

        #endregion
    }
}
